package com.chaos.eurekaproducer.utils;

import org.slf4j.MDC;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;

/**
 * @author liaopeng
 * @title: MyAsyncConfigurer
 * @projectName eureka-producer
 * @description: TODO
 * @date 2021/5/21下午2:59
 */
@Configuration
public class MyThreadPoolTaskExecutor{

    @Bean
    public Executor getExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(){
            @Override
            public <T> Future<T> submit(Callable<T> task) {
                Map<String, String> context = MDC.getCopyOfContextMap();
                return super.submit(() -> {
                    // 将父线程的MDC内容传给子线程
                    T result = null;
                    if(context!=null){
                        MDC.setContextMap(context);
                    }
                    try {
                        result = task.call();
                    } finally {
                        try {
                            MDC.clear();
                        } catch (Exception e2) {}
                    }
                    return result;
                });
            }
        };
        //线程池维护线程的最少数量
        taskExecutor.setCorePoolSize(3);
        //线程池维护线程的最大数量
        taskExecutor.setMaxPoolSize(300);
        //线程池所使用的缓冲队列
        taskExecutor.setQueueCapacity(5000);
        //线程池维护线程所允许的空闲时间
         taskExecutor.setKeepAliveSeconds(30000);
        return taskExecutor;
    }
}
